package com.stylefeng.guns.modular.huamao.controller;

import java.math.BigDecimal;
import java.util.*;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.modular.huamao.model.*;
import com.stylefeng.guns.modular.huamao.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.util.ToolUtil;
import com.stylefeng.guns.modular.huamao.result.Result;

/**
 * 订单管理控制器
 *
 * @author caody
 * @Date 2018-04-14 12:01:12
 */
@CrossOrigin()
@Controller
@RequestMapping("/sktOrders")
public class SktOrdersController extends BaseController {

    private String PREFIX = "/huamao/sktOrders/";

    @Autowired
    private ISktOrdersService sktOrdersService;

    @Autowired
    IUsersAddressService usersAddressService;
    @Autowired
    ISktShopFreightsService sktShopFreightsService;

    @Autowired
    IGoodsSpecsService specsService;

    @Autowired
    ISpecItemsService specItemsService;

    @Autowired
    ISpecCatsService specCatsService;

    @Autowired
    ISktOrderGoodsService sktOrderGoodsService;


    /**
     * 跳转到订单管理首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "sktOrders.html";
    }

    /**
     * 跳转到订单管理首页
     */
    @RequestMapping(value = "/alllist")
    @ResponseBody
    public Object allList(SktOrdersList sktOrdersList) {

        Object test = sktOrdersService.selectOrderShops(sktOrdersList);

        return test;
    }

    /**
     * 跳转到添加订单管理
     */
    @RequestMapping("/sktOrders_add")
    public String sktOrdersAdd() {
        return PREFIX + "sktOrders_add.html";
    }

    /**
     * 跳转到订单详情
     */
    @RequestMapping("/sktOrdersShow/{sktOrdersId}")
    public String sktOrdersShow(@PathVariable Integer sktOrdersId, Model model) {
        model.addAttribute("sktOrdersId", sktOrdersId);
        return PREFIX + "sktOrders_show.html";
    }

    /**
     * 加载订单显示内容
     */
    @RequestMapping(value = "/sktOrders_load")
    @ResponseBody
    public Object sktOrdersLoad(Integer sktOrdersId) {
        return sktOrdersService.selectById(sktOrdersId);
    }

    /**
     * 加载商品显示内容
     */
    @RequestMapping(value = "/sktOrdersGoods_load")
    @ResponseBody
    public Object sktOrdersGoodsLoad(Integer sktOrdersId) {
        return sktOrdersService.selectOrderGoods(sktOrdersId);
    }

    /**
     * 加载商品参数显示内容
     */
    @RequestMapping(value = "/sktOrdersGoodsParameter_load")
    @ResponseBody
    public Object sktOrdersGoodsParameterLoad(Integer goodsId) {
        List<Map<String,String>> list = new ArrayList<Map<String, String>>();

        GoodsSpecs goodsSpecs = new GoodsSpecs();
        goodsSpecs = specsService.selectById(goodsId);
        if(goodsSpecs!=null){

            String specIds = goodsSpecs.getSpecIds();
            String[] parts = specIds.split(":");

            for(int i=0;i<parts.length;i++){
                SpecItems specItems = new SpecItems();
                specItems = specItemsService.selectById(Integer.parseInt(parts[i]));

                SpecCats specCats = new SpecCats();
                specCats = specCatsService.selectById(specItems.getCatId());

                Map<String,String> map = new HashMap<String, String>();
                map.put(specCats.getCatName(),specItems.getItemName());
                list.add(map);
            }
        }
        return list;
//        Map<String, Object> param = new HashMap<String, Object>();
//        param.put("goodsId", goodsId);
//        return sktOrdersService.selectOrderGoodsParameter(param);
    }

    /**
     * 跳转到订单详情
     */
    @RequestMapping("/sktOrders_update/{sktOrdersId}")
    public String sktOrdersUpdate(@PathVariable Integer sktOrdersId, Model model) {
        SktOrders sktOrders = sktOrdersService.selectById(sktOrdersId);
        model.addAttribute("item", sktOrders);
        LogObjectHolder.me().set(sktOrders);
        return PREFIX + "sktOrders_show.html";
    }

    /**
     * 获取订单管理列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String condition) {
        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        //return sktOrdersService.selecOrdertShops(paramMap);
        return sktOrdersService.selectList(null);
    }

    /**
     * 新增订单管理
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(SktOrders sktOrders) {
        sktOrdersService.insert(sktOrders);
        return SUCCESS_TIP;
    }

    /**
     * 删除订单管理
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer sktOrdersId) {
        sktOrdersService.deleteById(sktOrdersId);
        return SUCCESS_TIP;
    }

    /**
     * 修改订单管理
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(SktOrders sktOrders) {
        sktOrdersService.updateById(sktOrders);
        return SUCCESS_TIP;
    }

    /**
     * 订单管理详情
     */
    @RequestMapping(value = "/detail/{sktOrdersId}")
    @ResponseBody
    public Object detail(@PathVariable("sktOrdersId") Integer sktOrdersId) {
        return sktOrdersService.selectById(sktOrdersId);
    }

    /******************首页*******************/
    /**
     * 线上商城   orderNo订单编号 beginTime endTime orderStatus订单状态
     */
	@RequestMapping(value = "/selectUserOrders")
    @ResponseBody
    public Result selectUserOrders(SktOrdersList sktOrdersList,Integer pageNum) {
        PageHelper.startPage(pageNum, 12);
        List<Map<String, Object>> list = sktOrdersService.selectUserOrders(sktOrdersList);
        PageInfo<Map<String, Object>> info = new PageInfo<Map<String, Object>>(list);
        return Result.OK(list,info.getPages());
    }

    /**
     * 待付款 待收货 待评价
     */
    @RequestMapping(value = "/selectUserOrdersInfo")
    @ResponseBody
    public Result selectUserOrdersInfo(SktOrdersList sktOrdersList, Integer pageNum) {
        Map<String, Object> map = sktOrdersService.selectUserOrdersInfo(sktOrdersList);
        if (ToolUtil.isEmpty(map)) {
            return Result.EEROR("查询失败!");
        }
        return Result.OK(map);
    }

    /**
     * 根据userid查询默认路径
     */
    @RequestMapping(value = "/selectAddressByUserid")
    @ResponseBody
    public Result selectAddressByUserid(Integer userId, Integer isDefault, Integer addressId) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("isDefault", isDefault);
        map.put("userId", userId);
        map.put("addressId", addressId);
        try {
            List<Map<String, Object>> list = sktOrdersService.selectAddressByUserid(map);
            return Result.OK(list);
        } catch (Exception e) {
            // TODO: handle exception
            return Result.EEROR("查询失败");
        }

    }

    /**
     * 更新地址
     *
     * @param usersAddress
     * @return
     */
    @RequestMapping(value = "changeAddress")
    @ResponseBody
    public Result changeAddress(UsersAddress usersAddress) {
        try {
            /**
             * 如果修改的字段含有默认地址字段，需要把用户下的地址默认值都清空，在重新设置
             */
            if (usersAddress.getIsDefault() == 1) {
                this.changeIsDefault(usersAddress);
            }
            usersAddressService.updateById(usersAddress);
            return Result.OK("更新成功");
        } catch (Exception e) {
            return Result.EEROR("更新失败");
        }

    }

    /**
     * 更改默认地址
     *
     * @param usersAddress
     * @return
     */
    @RequestMapping(value = "/changeIsDefault")
    @ResponseBody
    public Result changeIsDefault(UsersAddress usersAddress) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userId", usersAddress.getUserId());
        map.put("addressId", usersAddress.getAddressId());
        if (sktOrdersService.changeIsDefault(map)) {
            return Result.OK("更新成功");
        } else {
            return Result.EEROR("查询失败");
        }

    }

    /**
     * 添加用户地址
     *
     * @param usersAddress
     * @return
     */
    @RequestMapping(value = "/addAddress")
    @ResponseBody
    public Result addAddress(UsersAddress usersAddress) {
        usersAddress.setDataFlag(1);
        usersAddress.setCreateTime(new Date());
        if (sktOrdersService.addAddress(usersAddress)) {
            return Result.OK("添加成功");
        } else {
            return Result.EEROR("添加失败");
        }
    }

    /**
     * 删除用户地址
     */
    @RequestMapping(value = "/deleteAddress")
    @ResponseBody
    public Result deleteAddress(Integer addressId) {
        try {
            UsersAddress usersAddress = new UsersAddress();
            usersAddress.setDataFlag(-1);
            usersAddressService.updateById(usersAddress);
            return Result.OK("删除成功");
        } catch (Exception e) {
            return Result.EEROR("删除失败");
        }

    }

    /**
     * 订单初始化内容
     * @param param
     * @return
     */
    @RequestMapping(value = "/orderInit")
    @ResponseBody
    public Result orderInit(String param){
        List<Map<String, Object>> listMap = JSON.parseObject(param, new TypeReference<List<Map<String, Object>>>() {
        });
        JSONArray jsonArray = new JSONArray();
        for(Map<String,Object> map:listMap){
            Integer sktOrdersId = Integer.parseInt(map.get("sktOrdersId").toString());
            SktOrders rsktOrders = sktOrdersService.selectById(sktOrdersId);
            String orderNo = rsktOrders.getOrderNo();
            BigDecimal totalMoney = rsktOrders.getTotalMoney();
            String userAddress = rsktOrders.getUserAddress();
            String invoiceClient = rsktOrders.getInvoiceClient();
            Date createTime = rsktOrders.getCreateTime();
            BigDecimal perKaiyuan=rsktOrders.getKaiyuan();
            BigDecimal payTotalShopping=rsktOrders.getTotalShopping();
            /**
             * 获取积分跟商品名称
             */
            SktOrderGoods sktOrderGoods = new SktOrderGoods();
            sktOrderGoods.setOrderId(sktOrdersId);
            EntityWrapper<SktOrderGoods>  entityWrapper = new EntityWrapper<SktOrderGoods>(sktOrderGoods);
            List<SktOrderGoods> list= sktOrderGoodsService.selectList(entityWrapper);
            BigDecimal score = new BigDecimal("0");
            List<String>  goodsName = new ArrayList<String>();
            for(SktOrderGoods sktOrderGoods1:list){
                score = score.add(sktOrderGoods1.getScore());
                goodsName.add(sktOrderGoods1.getGoodsName());
            }

            JSONObject object = new JSONObject();
            object.put("orderNo",orderNo);
            object.put("totalMoney",totalMoney);
            object.put("userAddress",userAddress);
            object.put("invoiceClient",invoiceClient);
            object.put("paymentTime",createTime);
            object.put("score",score);
            object.put("goodsName",goodsName);
            object.put("perKaiyuan",perKaiyuan);
            object.put("payTotalShopping",payTotalShopping);
            jsonArray.add(object);
        }
        return Result.OK(jsonArray);
    }


    /**
     * 提交订单
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/submitOrder")
    @ResponseBody
    public Result submitOrder(String param, SktOrders sktOrders) {

        List<Map<String, Object>> listMap = JSON.parseObject(param, new TypeReference<List<Map<String, Object>>>() {
        });

        Boolean b = sktOrdersService.submitOrder(listMap, sktOrders);

        if (b) {
            return Result.OK("操作成功");
        } else {
            return Result.EEROR("操作失败");
        }

    }

    /**
     * 加载商品显示内容
     */
    @RequestMapping(value = "/showOrdersGoodsLoad")
    @ResponseBody
    public Result showOrdersGoodsLoad(Integer sktOrdersId) {
            try {
    		Object object = sktOrdersService.selectOrderGoods(sktOrdersId);
    		return Result.OK(object);
		} catch (Exception e) {
			// TODO: handle exception
			return Result.EEROR("查询失败");
		}
    }

    /**
     * 获取运费
     */
    @RequestMapping(value = "/getFreight")
    @ResponseBody
    public Result getFreight(@RequestParam(value = "shopIds[]")List<Integer> shopIds,@RequestParam(value = "cityId")Integer cityId) {
        try {
            //通过传来的商家id 和市级id查询运费
            Set set = new HashSet();
            List<Integer> listNew=new ArrayList<>();
            set.addAll(shopIds);
            listNew.addAll(set);
            List<Map<String,Object>> list  = sktShopFreightsService.getFreight(listNew,cityId);
            if(list != null && list.size() > 0){
                return Result.OK(list);
            }else{
                return Result.OK(0);
            }
        } catch (Exception e) {
            return Result.EEROR("查询失败");
        }
    }

    //获取地址

//    @RequestMapping(value = "/showOrdersGoodsLoad")
//    @ResponseBody
//    public Result showOrdersGoodsLoad(String sktOrdersId,String cityId) {
//    	Map<String,Object> param = new HashMap<String,Object>();
//    	param.put("sktOrdersId", sktOrdersId);
//    	param.put("cityId",cityId);
//    	try {
//    		Object object = sktOrdersService.selectOrderGoods(param);
//    		return Result.OK(object);
//		} catch (Exception e) {
//			return Result.EEROR("查询失败");
//		}
//    }
    /**
     * 加载商品参数显示内容
     */
    @RequestMapping(value = "/showOrdersGoodsParameter_load")
    @ResponseBody
    public Result showOrdersGoodsParameterLoad(Integer goodsId) {
    	Map<String,Object> param = new HashMap<String,Object>();
    	param.put("goodsId", goodsId);
    	try {
    		Object object = sktOrdersService.selectOrderGoodsParameter(param);
    		return Result.OK(object);
		} catch (Exception e) {
			// TODO: handle exception
			return Result.EEROR("查询失败");
		}
    }
    /**
     * 修改快递订单（商家发货）
     */
    @RequestMapping(value = "/updateOrdersStatus")
    @ResponseBody
    public Result updateOrdersStatus(SktOrders sktOrders) {
        JSONObject json = sktOrdersService.addExpressNo(sktOrders);
        return Result.OK(json);
    }

}
